package net.didactylos.helpline.servlet;

import java.text.SimpleDateFormat;
import java.util.Date;

import net.sourceforge.stripes.util.Log;

public class AgeFormatter
{
	private static final Log log = Log.getInstance(AgeFormatter.class);
	private static final String[] NAMES = new String[] {"day", "hour", "minute", "second"};

	public static String format(Date date)
	{
		//log.debug(date, date.getTime());
		Date now = new Date();
		// Age in seconds
		long age = (now.getTime() - date.getTime()) / 1000;
		int[] fields = getTimeFields(age);
		//log.debug(fields);
		
		if (fields[0] > 7)
		{
			// Over a week old. Give an absolute date.
			return new SimpleDateFormat("dd MMMM yyyy").format(date);
		}

		for (int i = 0; i < fields.length; i++)
		{
			if ((fields[i] > 0) && (i < NAMES.length))
			{
				StringBuilder s = new StringBuilder();
				s.append(fields[i]);
				s.append(' ');
				s.append(NAMES[i]);
				s.append((fields[i] != 1) ? "s ago" : " ago");
				return s.toString();
			}
		}
		// All fields zero - times less than a second apart.
		return "now";
	}
	
	private static int[] getTimeFields(long time)
	{
		int[] fields = new int[] {24, 60, 60, 1};
		int factor = 1;
		
		for (int i = 0;  i < fields.length; i++)
		{
			factor *= fields[i];
		}
		
		for (int i = 0;  i < fields.length; i++)
		{
			int field = (int) (time / factor);
			time = time % factor;
			factor /= fields[i];
			fields[i] = field;
		}
		return fields;
	}
}
